<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dataForm.shopBankCardId ? $t('admin.modifyAcc') : $t('shopProcess.addSettlementAccount')"
    :close-on-click-modal="false"
    :append-to-body="true"
    width="600px"
    @close="onCloseDialog"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="rules"
      label-width="auto"

      @submit.prevent
    >
      <el-form-item
        v-if="paySettlementType===1"

        prop="bankCardPro"
        :label="$t('allinpay.accountType')"
      >
        <el-radio-group v-model="dataForm.bankCardPro">
          <el-radio
            :disabled="!(legalCardNumber<1)"
            :label="0"
          >
            {{ $t('allinpay.corporateAccount') }}
          </el-radio>
          <el-radio
            :disabled="!(cardNumber<10)"
            :label="1"
          >
            {{ $t('allinpay.companyAccount') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===1&&dataForm.bankCardPro===1"

        prop="parentBankName"
        :label="$t('allinpay.bankName')"
      >
        <el-select
          v-model="selectBank"
          filterable
          :placeholder="$t('allinpay.pleaseSelect')"
          style="width:100%"
          @change="onChangeBank"
        >
          <el-option
            v-for="item in bankList"
            :key="item.bankId"
            :label="item.bankName"
            :value="item.bankName"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===1&&dataForm.bankCardPro===1"

        prop="bankName"
        :label="$t('allinpay.branchName')"
      >
        <el-input
          v-model.trim="dataForm.bankName"
          :placeholder="$t('allinpay.forExample') + '“中国工商银行股份有限公司北京樱桃园支行”'"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===1&&dataForm.bankCardPro===1"

        prop="accountNo"
        :label="$t('allinpay.businessPublicAccounts')"
      >
        <el-input
          v-model.trim="dataForm.accountNo"
          :placeholder="$t('allinpay.pleaseEntePublicAccount')"
          maxlength="19"
          @input="(val)=>{ dataForm.accountNo = val.replace(/[^\d]/g,'') }"
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===1&&dataForm.bankCardPro===1"

        prop="unionBank"
        :label="$t('allinpay.paymentLineNumber')"
      >
        <el-input
          v-model.trim="dataForm.unionBank"
          :placeholder="$t('allinpay.enterLineNumber')"
          maxlength="12"
          @input="(val)=>{ dataForm.unionBank = val.replace(/[^\d]/g,'') }"
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===0"
        prop="bankName"
        :label="$t('shopProcess.bankName')"
      >
        <el-input
          v-model="dataForm.bankName"
          :placeholder="$t('shopProcess.brandNameInputTips')"
          maxlength="20"
          @blur="
            dataForm.bankName =
              dataForm.bankName ?
                removeHeadAndTailSpaces(dataForm.bankName) :
                dataForm.bankName
          "
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===0"
        prop="openingBank"
        :label="$t('shopProcess.openingBank')"
      >
        <el-input
          v-model="dataForm.openingBank"
          :placeholder="$t('shopProcess.openingBankErrorTips')"
          maxlength="20"
          @blur="
            dataForm.openingBank =
              dataForm.openingBank ?
                removeHeadAndTailSpaces(dataForm.openingBank) :
                dataForm.openingBank
          "
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===0"
        prop="recipientName"
        :label="$t('shopProcess.recipientName')"
      >
        <el-input
          v-model="dataForm.recipientName"
          :placeholder="$t('shopProcess.recipientNameInputTips')"
          maxlength="20"
          @blur="
            dataForm.recipientName =
              dataForm.recipientName ?
                removeHeadAndTailSpaces(dataForm.recipientName) :
                dataForm.recipientName
          "
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===0||(paySettlementType===1&&dataForm.bankCardPro===0)"
        prop="cardNo"
        :label="$t('shopProcess.account')"
      >
        <el-input
          v-model="dataForm.cardNo"
          maxlength="30"
          :placeholder="$t('shopProcess.cardNoInputTips')"
          oninput="value=value.replace(/[^\d]/g,'')"
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===1&&dataForm.bankCardPro===0"

        prop="identityNo"
        :label="$t('allinpay.identityCard')"
      >
        <el-input
          v-model="dataForm.identityNo"
          :placeholder="$t('allinpay.pleaseEnterIdentityCard')"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item
        v-if="paySettlementType===1&&dataForm.bankCardPro===0"

        prop="mobile"
        :label="$t('allinpay.mobile')"
      >
        <el-input
          v-model="dataForm.mobile"
          :placeholder="$t('allinpay.pleaseEnterCardPhone')"
          maxlength="11"
          @input="(val)=>{ dataForm.mobile=val.replace(/[^\d]/g,'') }"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div

        class="btn-row"
      >
        <div
          class="default-btn"
          @click="dialogVisible = false"
        >
          {{ $t('shopProcess.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit"
        >
          {{ $t('shopProcess.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { removeHeadAndTailSpaces, checkIDCard, isMobile } from '@/utils/validate'
import { Debounce } from '@/utils/debounce'

const emit = defineEmits(['refreshDataList'])
const props = defineProps({
  cardNumber: {
    type: Number,
    default: 0
  },
  legalCardNumber: {
    type: Number,
    default: 0
  }
})

const validEmptyTab = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}
const validateMobile = (rule, value, callback) => {
  if (!isMobile(value)) {
    callback(new Error($t('allinpay.InputCorrectPhone')))
  } else {
    callback()
  }
}
const validIDCard = (rule, value, callback) => {
  if (!value || !checkIDCard(value)) {
    callback(new Error($t('allinpay.PleaseEnterCorporateIDCard')))
  } else {
    callback()
  }
}
const rules = reactive({
  bankName: [
    { required: true, message: $t('shopProcess.brandNameNotEmpty'), trigger: 'blur' },
    { min: 2, max: 20, message: $t('shopProcess.brandNameErrorTips'), trigger: 'blur' },
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  recipientName: [
    { required: true, message: $t('shopProcess.recipientNameNotEmpty'), trigger: 'blur' },
    { min: 2, max: 20, message: $t('shopProcess.recipientNameInputTips'), trigger: 'blur' },
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  cardNo: [
    { required: true, message: $t('shopProcess.accountNotEmpty'), trigger: 'blur' },
    { min: 8, max: 30, message: $t('shopProcess.bankCardInputTips'), trigger: 'blur' },
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  openingBank: [
    { required: true, message: $t('shopProcess.openingBankNotEmpty'), trigger: 'blur' },
    { min: 2, max: 20, message: $t('shopProcess.openingBankErrorTips'), trigger: 'blur' },
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  identityNo: [
    { required: true, message: $t('allinpay.IDCardNumberEmpty'), trigger: 'blur' },
    { validator: validIDCard, trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: $t('allinpay.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ],
  unionBank: [
    { required: true, message: $t('allinpay.enterLineNumber'), trigger: 'blur' },
    { min: 12, max: 12, message: $t('allinpay.pleaseEnterDigits'), trigger: 'blur' }
  ],
  parentBankName: [
    { required: true, message: $t('allinpay.pleaseEnterBankName'), trigger: 'change' }
  ],
  accountNo: [
    { required: true, message: $t('allinpay.companyNotEmpty'), trigger: 'blur' }
  ]
})

const allinpayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})

const dialogVisible = ref(false)
const dataForm = ref({
  bankName: '',
  recipientName: '',
  cardNo: '',
  openingBank: '',
  isDefault: 0,
  shopBankCardId: null,
  // 以下为通联支付
  mobile: '', // 银行预存手机号
  bankCardPro: props.cardNumber < 10 ? 1 : 0, // 银行卡类型 0：法人账户 1：对公账户
  unionBank: '', // 支付行号
  accountNo: '', // 企业对公账户
  parentBankName: '', // 银行名称
  identityNo: '' // 身份证号
})
const init = (shopBankCardId) => {
  dialogVisible.value = true
  nextTick(() => {
    if (paySettlementType.value === 1) {
      onGetBankList()
    }
    dataFormRef.value?.resetFields()
    dataForm.value.shopBankCardId = shopBankCardId || null
    if (!shopBankCardId) {
      return
    }
    http({
      url: http.adornUrl('/shop/shopBankCard'),
      method: 'get',
      params: http.adornParams({
        shopBankCardId: dataForm.value.shopBankCardId
      })
    }).then(({ data }) => {
      dataForm.value = data
    })
  })
}

/**
 * 创建或修改账号
 */
let submitFormLoading = false // 订单提交中
const onSubmit = Debounce(() => {
  if (submitFormLoading) return
  dataFormRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    submitFormLoading = true
    let request
    if (paySettlementType.value === 1) {
      // 通联支付
      if (dataForm.value.bankCardPro === 1) {
        // 对公账户
        const dataFormValue = {
          accountNo: dataForm.value.accountNo,
          bankName: dataForm.value.bankName,
          parentBankName: dataForm.value.parentBankName,
          unionBank: dataForm.value.unionBank
        }
        request = http({
          url: http.adornUrl('/shop/allinpay/company/bindCompanyAccount'),
          method: 'post',
          data: http.adornData(dataFormValue)
        })
      } else {
        // 法人账户
        const dataFormValue = {
          cardNo: dataForm.value.cardNo,
          phone: dataForm.value.mobile,
          identityNo: dataForm.value.identityNo
        }
        request = http({
          url: http.adornUrl('/shop/allinpay/company/applyBindBankCard'),
          method: 'post',
          data: http.adornData(dataFormValue)
        })
      }
    } else {
      request = http({
        url: http.adornUrl('/shop/shopBankCard'),
        method: dataForm.value.shopBankCardId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      })
    }
    request.then(() => {
      ElMessage({
        message: $t('shopProcess.saveSuccessfully'),
        type: 'success',
        duration: 1000
      })
      dialogVisible.value = false
      emit('refreshDataList')
      dataFormRef.value?.resetFields()
    }).finally(() => {
      submitFormLoading = false
    })
  })
}, 1500)

// 获取银行列表
const bankList = ref([])
const onGetBankList = () => {
  http({
    url: http.adornUrl('/publicBank/list'),
    method: 'get'
  }).then(({ data }) => {
    bankList.value = data
  })
}

const onChangeBank = (val) => {
  dataForm.value.parentBankName = val
}
const dataFormRef = ref(null)
const selectBank = ref('')
const onCloseDialog = () => {
  selectBank.value = ''
  dataFormRef.value?.resetFields()
}
defineExpose({
  init
})
</script>
